package com.youhong.teethcare;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jstyle.countrylibrary.CountryPage;
import com.mob.tools.FakeActivity;
import com.youhong.teethcare.netbeans.HttpReturn;
import com.youhong.teethcare.netbeans.LoginServerInterface;

import java.util.HashMap;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.smssdk.SMSSDK;

public class RetrieveActivity extends Activity implements CompoundButton.OnCheckedChangeListener {

    @BindView(R.id.login_btn_login)
    Button btn_login;
    @BindView(R.id.login_iv_emailPhoneIcon)
    ImageView iv_emailPhoneIcon;
    @BindView(R.id.login_rg)
    RadioGroup rg;
    @BindView(R.id.login_et_email)
    EditText et_email;
    @BindView(R.id.login_et_password)
    EditText et_password;
    @BindView(R.id.login_tv_areaCode)
    TextView tv_areaCode;
    @BindView(R.id.register_btn_verifyCode)
    Button btn_verifyCode;
    @BindView(R.id.register_et_checkCode)
    EditText et_checkCode;
    private CountDownTimer countDownTimer;
    boolean isCheckCode = true;
    RelativeLayout ll_input_password;
    LinearLayout ll_input_email;
    RelativeLayout rl_input_Code;
    @BindView(R.id.tvRegisterTips)
    TextView tvRegisterTips;
    @BindView(R.id.login_et_ConfirmPassword)
    EditText et_ConfirmPassword;
    @BindView(R.id.CheckBox_PsdShow)
    CheckBox CheckBoxPsdShow;
    @BindView(R.id.CheckBox_PsdShowConfim)
    CheckBox CheckBoxPsdShowConfim;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrieve);
        ButterKnife.bind(this);
        ll_input_password=findViewById(R.id.ll_input_password);
        ll_input_email=findViewById(R.id.ll_input_Email);
        rl_input_Code=findViewById(R.id.rl_input_Code);

        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                if (checkedId == R.id.login_rb_email) {
                    iv_emailPhoneIcon.setImageDrawable(
                            getResources().getDrawable(R.mipmap.icon_email_input));
                    tv_areaCode.setVisibility(View.GONE);
                    et_email.setHint(R.string.string_login3);
                } else {
                    iv_emailPhoneIcon.setImageDrawable(
                            getResources().getDrawable(R.mipmap.icon_phone_input));
                    tv_areaCode.setVisibility(View.VISIBLE);
                    et_email.setHint(R.string.string_login4);

                }
                et_email.setText("");
                et_password.setText("");

            }
        });
        showPsd();
    }
    void showPsd() {
        CheckBoxPsdShow.setOnCheckedChangeListener(this);
        CheckBoxPsdShowConfim.setOnCheckedChangeListener(this);
    }
    @OnClick({R.id.login_btn_login, R.id.login_tv_areaCode, R.id.register_btn_verifyCode})
    public void onClick(View view) {

        switch (view.getId()) {

            case R.id.login_btn_login: {
                if(isCheckCode){
                    checkCode();
                }else {
                    Retrieve();
                }

            }
            break;

            case R.id.login_tv_areaCode: {
                getCountryCode();
            }
            break;
            case R.id.register_btn_verifyCode: {

                GetCode();

            }
        }

    }
    public final static String ZH_CN = "zh";
    public final static String ZH_EN = "en_zh";
    void checkCode() {
        Locale locale = getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        String type = language.equals("zh") ? ZH_CN : ZH_EN;
        String account = et_email.getText().toString().trim();
        String checkCode = et_checkCode.getText().toString().trim();
        if (TextUtils.isEmpty(account)
                || TextUtils.isEmpty(checkCode)) {
            Toast.makeText(
                    this,
                    getResources()
                            .getString(R.string.string_login11),
                    Toast.LENGTH_SHORT).show();
            return;
        }
        if (rg.getCheckedRadioButtonId() == R.id.login_rb_phone) {
            String counrtyCode = tv_areaCode.getText().toString().replace("+", "00");

            LoginServerInterface.checkCode(rg.getCheckedRadioButtonId() == R.id.login_rb_email,
                    counrtyCode + "-" + account, checkCode, checkCode_callback);
        } else {

            LoginServerInterface.checkCode(rg.getCheckedRadioButtonId() == R.id.login_rb_email,
                    account, checkCode, checkCode_callback);
        }
    }
    LoginServerInterface.DefaultCallbackInterface checkCode_callback = new LoginServerInterface.DefaultCallbackInterface() {
        @Override
        public void callback(HttpReturn mReturn) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {


                    if (mReturn == null) {

                        Toast.makeText(RetrieveActivity.this,
                                R.string.strings30, Toast.LENGTH_SHORT).show();
                        return;
                    }


                    if (mReturn.getMsgCode() == 1) {
                        //Toast.makeText(RegisterActivity.this, "Successful", Toast.LENGTH_SHORT).show();
                        isCheckCode=false;

                        ll_input_password.setVisibility(View.VISIBLE);
                        ll_input_email.setVisibility(View.GONE);
                        rl_input_Code.setVisibility(View.GONE);
                        rg.setVisibility(View.GONE);
                        tvRegisterTips.setText(getString(R.string.retrieve_str2));
                    } else {

                        Toast.makeText(RetrieveActivity.this, LoginActivity.showResult(mReturn.getMsgCode(), RetrieveActivity.this)
                                , Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    };

    private void getCountryCode() {

        CountryPage phone = new CountryPage();
        phone.setCountryId("1");
        // Typeface typeface = Typeface.createFromAsset(getAssets(), "SourceHanSansCN-Regular.ttf");
        // phone.setTypeFace(typeface);
        phone.showForResult(this, (Intent) null, new FakeActivity() {
            @Override
            public void onResult(HashMap<String, Object> data) {
                super.onResult(data);
                if (null != data && null != data.get("id")) {
                    String currentId = (String) data.get("id");

                    if (CountryPage.Result_OK == (int) data.get("result")) {
                        String[] res = SMSSDK.getCountry(currentId);
                        tv_areaCode.setText("+" + res[1]);
                        //countryCode = "00" + res[1] + "-";
                    }
                }

            }
        });
    }

    private void GetCode() {
        String account = et_email.getText().toString().trim();

        if (TextUtils.isEmpty(account)) {
            Toast.makeText(
                    this,
                    getResources()
                            .getString(R.string.string_login11),
                    Toast.LENGTH_SHORT).show();
            return;
        }
        Locale locale = getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        LoginServerInterface.RequestType requestType = language.equals("zh") ?LoginServerInterface.RequestType.ChineseRetrieve:LoginServerInterface.RequestType.EnglishRetrieve;
        if (rg.getCheckedRadioButtonId() == R.id.login_rb_phone) {
            String counrtyCode = tv_areaCode.getText().toString().replace("+", "00");
            LoginServerInterface.PhoneVerficationCode(requestType, counrtyCode + "-" + account, getCode_callback);
        } else {
            LoginServerInterface.EmailVerficationCode(requestType, account, getCode_callback);
        }
    }

    private void Retrieve() {

        String account = et_email.getText().toString().trim();
        String pwd = et_password.getText().toString().trim();
        String confirmPwd=et_ConfirmPassword.getText().toString();
        if (TextUtils.isEmpty(pwd)||TextUtils.isEmpty(confirmPwd)
        ) {
            Toast.makeText(
                    this,
                    getResources()
                            .getString(R.string.string_login11),
                    Toast.LENGTH_SHORT).show();
            return;
        }
        if(!pwd.equals(confirmPwd)){
            Toast.makeText(
                    this,
                    getResources()
                            .getString(R.string.sure_psd_same),
                    Toast.LENGTH_SHORT).show();
            return;
        }

        if (rg.getCheckedRadioButtonId() == R.id.login_rb_phone) {
            String counrtyCode = tv_areaCode.getText().toString().replace("+", "00");
            LoginServerInterface.Retrieve(rg.getCheckedRadioButtonId() == R.id.login_rb_email,
                    counrtyCode + "-" + account, pwd, retrieve_callback);
        } else {
            LoginServerInterface.Retrieve(rg.getCheckedRadioButtonId() == R.id.login_rb_email,
                    account, pwd, retrieve_callback);
        }

    }

    LoginServerInterface.DefaultCallbackInterface getCode_callback = new LoginServerInterface.DefaultCallbackInterface() {
        @Override
        public void callback(HttpReturn mReturn) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    if (mReturn == null) {

                        Toast.makeText(RetrieveActivity.this, R.string.strings30, Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (mReturn.getMsgCode() == 1) {
                      //  Toast.makeText(RetrieveActivity.this, "Successful", Toast.LENGTH_SHORT).show();
                        btn_verifyCode.setEnabled(false);

                        countDownTimer = new CountDownTimer(60_000, 1000) {
                            @Override
                            public void onTick(long millisUntilFinished) {
                                btn_verifyCode.setText(String.format(getString(R.string.getCodeForamt)
                                        , millisUntilFinished / 1000 + ""));
                            }

                            @Override
                            public void onFinish() {
                                btn_verifyCode.setText(getString(R.string.Get_verification_code));
                                btn_verifyCode.setEnabled(true);
                            }
                        };
                        countDownTimer.start();
                    } else {

                        Toast.makeText(RetrieveActivity.this, LoginActivity.showResult(mReturn.getMsgCode(), RetrieveActivity.this)
                                , Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    };

    LoginServerInterface.DefaultCallbackInterface retrieve_callback = new LoginServerInterface.DefaultCallbackInterface() {
        @Override
        public void callback(HttpReturn mReturn) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    if (mReturn == null) {

                        Toast.makeText(RetrieveActivity.this, R.string.strings30, Toast.LENGTH_SHORT).show();
                        return;
                    }


                    if (mReturn.getMsgCode() == 1) {
                        Toast.makeText(RetrieveActivity.this, "Successful", Toast.LENGTH_SHORT).show();
                        finish();

                    } else {

                        Toast.makeText(RetrieveActivity.this, LoginActivity.showResult(mReturn.getMsgCode(), RetrieveActivity.this)
                                , Toast.LENGTH_SHORT).show();
                    }


                }
            });
        }
    };

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        int id=buttonView.getId();
        EditText editText= null;
        if(id==R.id.CheckBox_PsdShow){
            editText=et_password;
        }else if(id==R.id.CheckBox_PsdShowConfim){
            editText=et_ConfirmPassword;
        }
        editText.setTransformationMethod(isChecked? HideReturnsTransformationMethod.getInstance(): PasswordTransformationMethod.getInstance());

    }
}
